package com.android.aiod.ui.fragment;

import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.android.baselibrary.interface_.CommCallBack;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.ui.BaseFragment;
import com.android.aiod.R;
import com.android.aiod.constants.Constants;
import com.android.aiod.manager.UserManager;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.BindView;

public class WebView_Fragment extends BaseFragment {

    @BindView(R.id.myProgressBar)
    ProgressBar myProgressBar;
    @BindView(R.id.webview)
    BridgeWebView webview;


    String url1 = "https://xyz.maoz.xyz/androidtest.html";
    String url4 = "https://xyz.maoz.xyz/androidtest2.html";


    String url2 = "http://101.43.90.15/demo.html";
    String url3 = "file:///android_asset/demo.html";

    public String url = "";
    public CommCallBack callBack;
    Handler handler = new Handler();

    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_webview;
    }

    @Override
    protected void initView() {
        initWebView();
    }

    @Override
    protected void initData() {
        this.url = UserManager.getUserInfo(mContext).h5url;

        if (!TextUtils.isEmpty(url)) {
            webview.loadUrl(url);
            Log.i("url:" + url);
        } else {
            CommToast.showToast(mContext, "URL地址为空");
        }
    }

    public void toJs() {
//        webview.loadUrl("javascript:alertInfo('123456')");
//        selectImg1();
//        webview.loadUrl(url);

        webview.callHandler("alertInfo", "123", new CallBackFunction() {
            @Override
            public void onCallBack(String data) {

            }
        });
    }

    private void initWebView() {
        WebSettings mWebSettings = webview.getSettings();
        String userAgent = webview.getSettings().getUserAgentString();
        if (!TextUtils.isEmpty(userAgent)) {
            webview.getSettings().setUserAgentString("Mozilla/5.0 (Linux; Android 7.1.1; 1801-A01 Build/NMF26X; wv)");
        }
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);  //提高渲染的优先级
//        mWebSettings.setBlockNetworkImage(true);
        mWebSettings.setJavaScriptEnabled(true);                    //  支持Javascript 与js交互
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);//  支持通过JS打开新窗口
        mWebSettings.setAllowFileAccess(true);                      //  设置可以访问文件
//        mWebSettings.setSupportZoom(true);                          //  支持缩放
//        mWebSettings.setBuiltInZoomControls(true);                  //  设置内置的缩放控件
//        mWebSettings.setUseWideViewPort(true);                      //  自适应屏幕

        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setLoadWithOverviewMode(true);

        mWebSettings.setAllowContentAccess(true);
        mWebSettings.setAllowFileAccessFromFileURLs(true);
        mWebSettings.setAllowUniversalAccessFromFileURLs(true);
        mWebSettings.setDatabaseEnabled(true);

        //自适应屏幕
//        mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        mWebSettings.setLoadWithOverviewMode(true);
//
//        mWebSettings.setSupportMultipleWindows(false);               //  多窗口
        mWebSettings.setDefaultTextEncodingName("utf-8");           //  设置编码格式
        mWebSettings.setAppCacheEnabled(true);
        mWebSettings.setDomStorageEnabled(true);  // 开启 localStorage
//        mWebSettings.setAppCacheMaxSize(Long.MAX_VALUE);
//        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);       //  缓存模式
        //设置不用系统浏览器打开,直接显示在当前WebView
        webview.setWebViewClient(new BridgeWebViewClient(webview) {

//            @Override
//            public boolean shouldOverrideUrlLoading(BridgeWebView view, String url) {
//                try {
//                    if (url.startsWith("http:") || url.startsWith("https:")) {
//                        view.loadUrl(url);
//                    } else {
//                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                        startActivity(intent);
//                    }
//                    Log.i("url:" + url);
////                    CommToast.showToast(mContext, "链接：" + url);
//                    return true;
//                } catch (Exception e) {
//                    return false;
//                }
//            }

//            @Override
//            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
//                Log.i("shouldInterceptRequest1: " + url);
//                String key = "https://xyz.maoz.xyz/storage";
//                WebResourceResponse response = null;
//                if (url.contains(key)) {
//                    try {
//                        String imgPath = url.replace(key, "");
////                        imgPath = Uri.parse(imgPath).getPath();
//                        InputStream localCopy = new FileInputStream(imgPath);
//                        //当前只针对图片
//                        response = new WebResourceResponse("image/png", "UTF-8", localCopy);
//                        Log.i("shouldInterceptRequest:" + imgPath);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                    return response;
//                }
//                return super.shouldInterceptRequest(view, url);
//            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                Log.i("shouldInterceptRequest2:" + request.getUrl().toString());
                String requesturl = request.getUrl().toString();
                String key = Constants.Host + "/localfile";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && requesturl.contains(key)) {
                    WebResourceResponse response = null;
                    try {
                        String imgPath = requesturl.replace(key, "");
//                            String imgPath = "//storage/emulated/0/DCIM/Screenshots/Screenshot_2022-08-18-19-23-49-876_com.android.didida.jpg";
                        Log.i("imgPath:" + imgPath);
//                            imgPath = Uri.parse(imgPath).getPath();
                        InputStream localCopy = new FileInputStream(imgPath);
                        //当前只针对图片
                        response = new WebResourceResponse("image/png", "UTF-8", localCopy);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return response;
                }
                return super.shouldInterceptRequest(view, request);
            }
        });
//        // 选择图片
//        webview.registerHandler("selectImg", new BridgeHandler() {
//
//            @Override
//            public void handler(String data, CallBackFunction function) {
//                Log.i("data:" + data);
//                selectImg1(function);
//            }
//        });

    }

    class MyWebClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
//            myProgressBar.setProgress(newProgress);
//            if (myProgressBar != null) {
//                if (newProgress == 100) {
//                    myProgressBar.setVisibility(View.GONE);
//                    webview.getSettings().setBlockNetworkImage(false);
//                } else {
//                    if (View.GONE == myProgressBar.getVisibility()) {
//                        myProgressBar.setVisibility(View.VISIBLE);
//                    }
//                    myProgressBar.setProgress(newProgress);
//                }
//            }
        }

        @Override
        public void onReceivedTitle(WebView webView, String s) {
            super.onReceivedTitle(webView, s);
            Log.i("onReceivedTitle:" + s);
            if (callBack != null) {
                callBack.onResult(s);
            }
        }
    }

    public boolean onBackPressed() {
        if (webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return false;
    }


}
